package com.ndbg.demo.service.generator;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

public class MysqlGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("auther");
        gc.setOpen(false);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setFileOverride(true);//每次运行进行覆盖操作
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://110.40.138.138:3306/movie?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);


        String moduleName = scanner("模块名");
        // 包配置
        PackageConfig pc = new PackageConfig();
//        pc.setModuleName(moduleName);
        pc.setParent("com.ndbg.demo");//项目包路径
        pc.setController("gateway." + moduleName);
        pc.setMapper("service." + moduleName + ".dao");
        pc.setEntity("model");
        pc.setService("service." + moduleName + ".service");
        pc.setServiceImpl("service." + moduleName + ".service.impl");
        //设置不同类文件生成路径
        HashMap<String, String> pathMap = new HashMap<>();
        pathMap.put(ConstVal.CONTROLLER,projectPath+"/manage-business-gateway/src/main/java/com/hc/movie/gateway");
        pathMap.put(ConstVal.ENTITY,projectPath+"/manage-business-model/src/main/java/com/hc/movie/model");
        pathMap.put(ConstVal.MAPPER,projectPath+"/manage-business-service/src/main/java/com/hc/movie/service/" + moduleName);
        pathMap.put(ConstVal.SERVICE,projectPath+"/manage-business-service/src/main/java/com/hc/movie/service");
        pathMap.put(ConstVal.SERVICE_IMPL,projectPath+"/manage-business-service/src/main/java/com/hc/movie/service");
        pc.setPathInfo(pathMap);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.vm";
        String entityPath= "/templates/entity.java.vm";
        String mapperJavaPath = "/templates/mapper.java.vm";
        String servicePath = "/templates/service.java.vm";
        String serviceImplPath = "/templates/serviceImpl.java.vm";
        String controllerPath = "/templates/controller.java.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(entityPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义Entity文件名跟生成路径
                return projectPath + "/manage-business-model/src/main/java/com/hc/movie/model/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
            }
        });

        focList.add(new FileOutConfig(mapperJavaPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义Mapper文件名跟生成路径
                return projectPath + "/manage-business-service/src/main/java/com/hc/movie/service/" + moduleName + "/dao/" + tableInfo.getEntityName() + "Mapper" +StringPool.DOT_JAVA;
            }
        });

        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/manage-business-service/src/main/resources/mapping/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        focList.add(new FileOutConfig(servicePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义service文件名跟生成路径
                return projectPath + "/manage-business-service/src/main/java/com/hc/movie/service/" + moduleName + "/service/" + "I" + tableInfo.getEntityName() + "Service" +StringPool.DOT_JAVA;
            }
        });

        focList.add(new FileOutConfig(serviceImplPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义service文件名跟生成路径
                return projectPath + "/manage-business-service/src/main/java/com/hc/movie/service/" + moduleName + "/service/impl/" + tableInfo.getEntityName() + "ServiceImpl" +StringPool.DOT_JAVA;
            }
        });

        focList.add(new FileOutConfig(controllerPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义service文件名跟生成路径
                return projectPath + "/manage-business-gateway/src/main/java/com/hc/movie/gateway/" + moduleName + "/" + tableInfo.getEntityName() + "Controller" +StringPool.DOT_JAVA;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        //不生成如下类型模板
        templateConfig.setController(null);
        templateConfig.setService(null);
        templateConfig.setServiceImpl(null);
        templateConfig.setMapper(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
//        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}
